layui.use(['form', 'jquery', 'layer', 'laytpl'], function () {
    var form = layui.form,
        $ = layui.jquery,
        layer = layui.layer,
        laytpl = layui.laytpl; // ✅ 引入 laytpl 模块

    let loginAttempts = parseInt(localStorage.getItem('loginAttempts')) || 0;
    const maxAttempts = 5;

    const resetPasswordFormHTML = `
        <form class="layui-form" id="resetPasswordForm" lay-filter="resetPasswordForm">
            <div class="layui-form-item">
                <label class="layui-form-label"><i class="fa fa-user-circle-o"></i></label>
                <div class="layui-input-inline">
                    <input type="text" name="username" id="resetUsername" autocomplete="off" placeholder="用户名"
                           class="layui-input" readonly style="background-color: #f2f2f2;">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label"><i class="fa fa-lock"></i></label>
                <div class="layui-input-inline">
                    <input type="password" name="newPassword"
                    id="resetNewPassword"
                    autocomplete="new-password"
                    placeholder="新密码"
                           class="layui-input"
                            lay-verify="password">
                    <i class="fa fa-eye toggle-password" id="toggleResetPassword"></i>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="resetPasswordForm">确认重置</button>
                </div>
            </div>
        </form>
    `;

    const lockTime = 10 * 60 * 1000;
    let lockUntil = localStorage.getItem('lockUntil') ? new Date(localStorage.getItem('lockUntil')) : null;

    function checkLockStatus() {
        if (lockUntil && new Date() < lockUntil) {
            const remainingTime = Math.ceil((lockUntil - new Date()) / 60000);
            layer.msg(`由于多次登录失败，账号已被锁定 ${remainingTime} 分钟`, {icon: 2});
            $('.btn-login').attr('disabled', true).addClass('layui-btn-disabled');
            return true;
        } else {
            loginAttempts = 0;
            lockUntil = null;
            localStorage.removeItem('loginAttempts');
            localStorage.removeItem('lockUntil');
            $('.btn-login').attr('disabled', false).removeClass('layui-btn-disabled');
            return false;
        }
    }

    checkLockStatus();

    // 合并密码验证规则：同时满足两个页面的要求
    form.verify({
        username: function (value, item) {
            if (!value) {
                return '用户名不能为空';
            }
            if (!/^[a-zA-Z0-9_]{3,20}$/.test(value)) {
                return '用户名长度应在3到20个字符之间，只能包含字母、数字和下划线';
            }
        },
        password: function (value, item) {
            if (!value) {
                return '密码不能为空';
            }
            // 同时满足两个页面的密码规则
            if (!/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{6,20}$/.test(value)) {
                return '密码长度应在6到20个字符之间，需包含字母、数字和特殊字符';
            }
        }
    });

    $('#togglePassword').on('click', function () {
        const $passwordInput = $('#password');
        const type = $passwordInput.attr('type') === 'password' ? 'text' : 'password';

        $passwordInput.attr('type', type);
        $(this).toggleClass('fa-eye fa-eye-slash');
    });

    // 忘记密码功能
    $('#forgotPassword').on('click', function () {
        const username = $('#username').val();

        if (!username) {
            layer.prompt({
                title: '请输入您的用户名',
                formType: 0
            }, function (value, index, elem) {
                openResetPasswordPopup(value);
                layer.close(index);
            });
        } else {
            openResetPasswordPopup(username);
        }
    });

    // 打开重置密码弹窗
    function openResetPasswordPopup(username) {
        layer.open({
            title: '重置密码',
            type: 1,
            area: ['400px', '300px'],
            content: resetPasswordFormHTML,
            success: function (layero, index) {
                // 初始化表单
                layui.form.render();

                // 设置用户名为只读
                layero.find('#resetUsername').val(username);

                // 密码可见性切换
                layero.find('#toggleResetPassword').on('click', function () {
                    const $input = layero.find('#resetNewPassword');
                    const type = $input.attr('type') === 'password' ? 'text' : 'password';
                    $input.attr('type', type);
                    $(this).toggleClass('fa-eye fa-eye-slash');
                });

                // 监听表单提交事件
                layui.form.on('submit(resetPasswordForm)', function (data) {
                    const field = data.field;

                    $.ajax({
                        url: window.appConfig.apiBaseUrl + '/user/reset-password',
                        type: 'POST',
                        contentType: 'application/x-www-form-urlencoded',
                        data: {
                            username: field.username,
                            newPassword: field.newPassword
                        },
                        success: function (res) {
                            if (res.code===0) {
                                layer.msg('密码重置成功，请使用新密码登录', {icon: 1});
                                layer.close(index);
                            } else {
                                layer.msg(res.message || '密码重置失败，请重试', {icon: 2});
                            }
                        },
                        error: function () {
                            layer.msg('请求失败，请检查网络或联系管理员', {icon: 2});
                        }
                    });

                    return false;
                });
            }
        });
    }

    // 注册功能
    $('.register-btn').on('click', async function () {

        // 显示加载中
        const loadingIndex = layer.load(1, {shade: [0.5, '#000']});

        // 异步加载单位列表
        loadUnits().then(units => {
            layer.close(loadingIndex); // 关闭加载提示

            if (!units || units.length === 0) {
                layer.msg('获取单位列表失败，请稍后重试', {icon: 2});
                return;
            }
            // 使用 laytpl 渲染模板，并传入 units 数据
            const tpl = $('#registerTpl').html();
            const renderedHTML = laytpl(tpl).render({units: units});
            layer.open({
                title: '用户注册',
                type: 1,
                area: ['500px', '420px'],
                content: renderedHTML,
                success: function (layero, index) {
                    // 初始化表单和样式
                    layui.form.render();

                    // 密码强度检测
                    layero.find('#registerPassword').on('input', function () {
                        const password = $(this).val();
                        const strengthMeter = layero.find('#passwordStrength');
                        const strengthBars = strengthMeter.find('span:not(.strength-text)');
                        const strengthText = strengthMeter.find('.strength-text');

                        let strength = 0;
                        if (password.length >= 8) strength++;
                        if (password.length >= 12) strength++;
                        if (/[A-Za-z]/.test(password)) strength++;
                        if (/\d/.test(password)) strength++;
                        if (/[@$!%*#?&]/.test(password)) strength++;

                        strengthBars.css('background-color', '#eee');
                        if (strength >= 1) strengthBars.eq(0).css('background-color', '#ff5252');
                        if (strength >= 3) strengthBars.eq(1).css('background-color', '#ffeb3b');
                        if (strength >= 5) strengthBars.eq(2).css('background-color', '#4caf50');

                        let text = strength <= 2 ? '弱' : strength <= 4 ? '中' : '强';
                        strengthText.text(text)
                            .css('color', strength >= 5 ? '#4caf50' : strength >= 3 ? '#ffeb3b' : '#ff5252');
                    });

                    // 密码可见性切换
                    layero.find('#toggleRegisterPassword').on('click', function () {
                        const $input = layero.find('#registerPassword');
                        const type = $input.attr('type') === 'password' ? 'text' : 'password';
                        $input.attr('type', type);
                        $(this).toggleClass('fa-eye fa-eye-slash');
                    });

                    // 监听提交事件
                    layui.form.on('submit(registerForm)', function (data) {
                        const field = data.field;

                        $.ajax({
                            url: window.appConfig.apiBaseUrl +'/user',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(field),
                            success: function (res) {
                                if (res.code===0) {
                                    layer.msg('注册成功，请登录', {icon: 1});
                                    layer.close(index);
                                } else {
                                    layer.msg(res.message || '注册失败', {icon: 2});
                                }
                            },
                            error: function () {
                                layer.msg('请求失败，请检查网络', {icon: 2});
                            }
                        });

                        return false;
                    });
                }
            });
        }).catch(error => {
            layer.close(loadingIndex);
            console.error('获取单位列表失败:', error);
            layer.msg('获取单位列表失败，请检查网络连接', {icon: 2});
        });
    });

    // 键盘事件处理
    $('input').on('keyup', function (e) {
        if (e.key === 'Enter') {
            $('.btn-login').trigger('click');
        }
    });

    // 记住我功能 - 移除了自定义勾选框的点击事件处理
    // 现在直接使用原生勾选框的 change 事件

    // 页面加载时恢复记住的状态
    const remembered = localStorage.getItem('rememberMe');
    if (remembered) {
        $('#rememberMe').prop('checked', true);
    }

    // 全局缓存单位映射表
    let unitMap = {};

    // 异步加载单位列表
    async function loadUnits() {
        try {
            const res = await $.ajax({
                url: window.appConfig.apiBaseUrl + '/unit/all',
                method: 'GET'
            });

            if (res.code === 200|| res.code === "200" && Array.isArray(res.data)) {
                return res.data;
            } else {
                throw new Error("单位数据格式错误");
            }
        } catch (error) {
            console.error("加载单位失败:", error);
            layer.msg("加载单位失败，请检查网络或联系管理员");
            return [];
        }
    }

    // 登录表单提交
    form.on('submit(loginForm)', function (data) {
        if (checkLockStatus()) return false;

        const username = data.field.username;
        const password = data.field.password;

        const loadingIndex = layer.load(1, {shade: [0.5, '#000']});

        // 发送登录请求
        $.ajax({
            type: 'POST',
            url: window.appConfig.apiBaseUrl + '/user/login',
            data: {username, password},
            success: function (res) {
                layer.close(loadingIndex);

                if (res.data.success) {
                    // 登录成功，重置尝试次数
                    loginAttempts = 0;
                    localStorage.removeItem('loginAttempts');
                    localStorage.removeItem('lockUntil');

                    // 获取“记住我”状态
                    const rememberMe = $('#rememberMe').prop('checked');

                    // 如果用户选择“记住我”，则保存用户名
                    if (rememberMe) {
                        localStorage.setItem('rememberedUsername', username);
                        localStorage.setItem('rememberMe', 'true');
                    } else {
                        localStorage.removeItem('rememberedUsername');
                        localStorage.removeItem('rememberMe');
                    }

                    console.log('登录成功');
                    console.log('登录成功，用户名：' + username);
                    console.log('登录成功，密码：' + password);
                    console.log('登录成功，记住我：' + rememberMe);
                    console.log('登录成功，用户ID：' + res.data.userId);
                    console.log('登录成功，用户角色：' + res.data.isAdmin);
                    console.log('登录成功，单位ID：' + res.data.unitId);
                    // 存储用户信息
                    sessionStorage.setItem('username', username);
                    sessionStorage.setItem('isAdmin', res.data.isAdmin?'true':'false');
                    sessionStorage.setItem('unitId', res.data.unitId);
                    sessionStorage.setItem('userId', res.data.userId);


                    // 登录成功提示
                    layer.confirm('登录成功！', {
                        icon: 1,
                        title: '提示',
                        btn: ['进入系统']
                    }, function () {
                        if (res.data.isAdmin) {
                            window.location.href = '/admin.html';
                        } else {
                            window.location.href = '/user.html';
                        }
                    });
                } else {
                    // 登录失败，增加尝试次数
                    loginAttempts++;
                    localStorage.setItem('loginAttempts', loginAttempts);

                    if (loginAttempts >= maxAttempts) {
                        // 达到最大尝试次数，锁定账号
                        lockUntil = new Date();
                        lockUntil.setTime(lockUntil.getTime() + lockTime);
                        localStorage.setItem('lockUntil', lockUntil);

                        layer.msg(`登录失败，您已达到最大尝试次数，账号将被锁定10分钟`, {icon: 2});
                        $('.btn-login').attr('disabled', true).addClass('layui-btn-disabled');
                    } else {
                        layer.msg(`登录失败（剩余尝试 ${maxAttempts - loginAttempts} 次）`, {icon: 2});
                        $('#password').addClass('layui-form-danger');
                        setTimeout(() => {
                            $('#password').removeClass('layui-form-danger');
                        }, 2000);
                    }
                }
            },
            error: function () {
                layer.close(loadingIndex);
                layer.msg('请求失败，请检查网络', {icon: 2});
            }
        });

        return false;
    });

    // 页面加载时检查“记住我”
    const rememberedUsername = localStorage.getItem('rememberedUsername');
    if (rememberedUsername) {
        $('#username').val(rememberedUsername);
    }
});
